import Taro, { useDidShow } from '@tarojs/taro';
import BusinessConstant from '@/constant/BusinessConstant';
import { useEffect } from 'react';
import socketStore from '@/stores/SocketStore';
import userStore from '@/stores/UserStore';
import authStore from '@/stores/AuthStore';
import { eventCenter } from '@tarojs/runtime';
import EventConstant from '@/constant/EventConstant';
import AuthConstant from '@/constant/AuthConstant';
import useLandlord from './useLandlord';
import useReport from './useReport';
import useChat from './useChat';

export default function useSocket() {
  const { GET_PENDING_LEASE, GET_LANDLORD_REPORT, GET_SESSION_VARIOUS } =
    EventConstant;

  const { websocketInstance, setWebsocketInstance, clearWebsocketInstance } =
    socketStore;
  const { user } = userStore;
  const { identity } = authStore;

  const { getPendingLease } = useLandlord();
  const { getReportByLandlordId } = useReport();
  const { getChatSessionList } = useChat();

  /**
   * websocket 触发事件
   * @param data
   */
  const messageCallBack = ({ data }) => {
    try {
      const { active } = JSON.parse(data);
      if (active === BusinessConstant.SOCKET_GET_TENANT_LEASE_HOUSE) {
        // 获取租客租赁的房屋
        eventCenter.trigger(EventConstant.GET_TENANT_LEASE_HOUSE);
      } else if (active === BusinessConstant.SOCKET_GET_TENANT_REPORT) {
        // 获取租客的报修
        eventCenter.trigger(EventConstant.GET_TENANT_REPORT);
      } else if (active === BusinessConstant.SOCKET_GET_PENDING_LEASE) {
        // 获取待处理的租赁申请
        eventCenter.trigger(EventConstant.GET_PENDING_LEASE);
      } else if (active === BusinessConstant.SOCKET_GET_LANDLORD_REPORT) {
        // 重新获取房东的房屋维修（租客的报修申请）
        eventCenter.trigger(EventConstant.GET_LANDLORD_REPORT);
      } else if (active === BusinessConstant.SOCKET_GET_CHAT_MESSAGE) {
        // 获取聊天信息
        eventCenter.trigger(EventConstant.GET_CURRENT_LAST_ONE_MESSAGE);
        eventCenter.trigger(EventConstant.GET_SESSION_VARIOUS);
      }
    } catch (_) {}
  };

  /**
   * 订阅 websocket 监听事件
   */
  const subscribeWebSocket = () => {
    // 先取消这里所需要的事件订阅
    eventCenter.off(GET_PENDING_LEASE);
    eventCenter.off(GET_LANDLORD_REPORT);
    eventCenter.off(GET_SESSION_VARIOUS);

    // 租客
    if (identity === AuthConstant.TENANT) {
    }
    // 房东
    else if (identity === AuthConstant.LANDLORD) {
      // 获取待处理的租赁申请
      eventCenter.on(GET_PENDING_LEASE, () => {
        getPendingLease();
      });
      // 重新获取房东的房屋维修（租客的报修申请）
      eventCenter.on(GET_LANDLORD_REPORT, () => {
        user?.id && getReportByLandlordId(user?.id);
      });
    }
    // 有人发信息，则需要重新获取 对话列表、对话最新消息、对方信息
    eventCenter.on(GET_SESSION_VARIOUS, async () => {
      // 重新获取 session 对话列表
      await getChatSessionList();
    });
  };

  /**
   * 链接 websocket 的逻辑处理
   * @param onMessageCallBack 监听服务器发送过来的数据
   */
  const useConnectWebSocket = async () => {
    /**
     * 链接chat聊天时的websocket
     * @param identity 身份（房东或者租客身份）
     * @param userId 用户id
     */
    const connectChatSocket = async (identity: string, userId: number) => {
      const socket = await Taro.connectSocket({
        url: `${BusinessConstant.WEBSOCKET_SERVER}?${identity}=${userId}`,
      });
      !websocketInstance && setWebsocketInstance(socket);
      // 监听事件
      subscribeWebSocket();
    };

    useEffect(() => {
      !websocketInstance &&
        user?.id &&
        identity &&
        connectChatSocket(identity, user?.id);
    }, [user?.id]);

    useEffect(() => {
      // 监听服务端的消息
      if (websocketInstance) {
        websocketInstance.onMessage(messageCallBack);
      }
      // 监听链接是否断开
      websocketInstance &&
        websocketInstance.onClose(() => {
          clearWebsocketInstance();
        });
    }, [websocketInstance]);

    useDidShow(() => {
      !websocketInstance &&
        user?.id &&
        identity &&
        connectChatSocket(identity, user?.id);
    });
  };

  /**
   * 获取 websocket 的消息
   */
  const getWebSocketMessage = () => {
    // 租客
    if (identity === AuthConstant.TENANT) {
    }
    // 房东
    else if (identity === AuthConstant.LANDLORD) {
      // 获取待处理的租赁申请
      getPendingLease();
      // 获取房东的房屋报修（租客的报修记录）
      user?.id && getReportByLandlordId(user?.id);
    }
    getChatSessionList();
  };

  return {
    useConnectWebSocket,
    getWebSocketMessage,
  };
}
